package com.event.controller;

import com.event.exception.UploadException;
import com.event.result.Result;
import com.event.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
	
	/**
	 * 文件上传
	 */
	@PostMapping
	public Result<String> upload(MultipartFile file) {
		log.info("文件上传：{}", file);
		try {
			// 生成唯一文件名
			String name = "big-event/" +
				UUID.randomUUID() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
			return Result.success(AliOssUtil.uploadFile(name, file.getBytes()));
		} catch (IOException e) {
			return Result.error(UploadException.UPLOAD_FILE_ERROR);
		}
	}
}
